<template>
  <div class="pest-management-container">
    <!-- 新增视频直播区域 -->
    <div class="video-section">
      <div class="video-container">
        <video
            ref="videoPlayer"
            class="video-js vjs-big-play-centered"
            preload="auto"
        ></video>
        <!--        <MonitorRealtime></MonitorRealtime>-->
        <div class="screenshot-btn">
          <el-button
              type="success"
              :icon="Camera"
              circle
              @click="captureSnapshot"
          />
        </div>
      </div>
    </div>

    <!-- 上传区域 -->
    <el-upload
        class="upload-container"
        drag
        action="#"
        :auto-upload="false"
        :show-file-list="false"
        :on-change="handleImageUpload"
        accept="image/*"
    >
      <template #default>
        <div class="upload-content">
          <el-icon class="upload-icon"><upload-filled /></el-icon>
          <div class="upload-text">
            <p class="upload-main">上传病虫害图片</p>
            <p class="upload-sub">支持JPG/PNG/BMP等很多种图片格式，大小不超过{{ maxMB }}MB</p>
          </div>
        </div>
      </template>
    </el-upload>

    <div class="main-content">
      <!-- 图片预览与结果 -->
      <div class="analysis-section">
        <div class="image-preview">
          <div v-if="uploadedImage" class="preview-card">
            <img :src="uploadedImage" alt="Preview" />
            <div class="image-info">
              <span class="file-name">{{ fileName }}</span>
              <span class="upload-time">{{ uploadTime }}</span>
            </div>
          </div>
          <div v-else class="empty-preview">
            <el-icon><picture-filled /></el-icon>
            <p>等待上传图片</p>
          </div>
        </div>

        <div class="result-display">
          <el-card v-if="result" class="result-card">
            <template #header>
              <div class="card-header">
                <h3 class="disease-name">{{ result.name }}</h3>
                <el-tag type="success" effect="dark" round>
                  {{ (result.confidence).toFixed(1) }}%
                </el-tag>
              </div>
            </template>

            <el-descriptions :column="1">
              <el-descriptions-item label="病害特征">
                <div class="description-text">{{ result.description }}</div>
              </el-descriptions-item>
              <el-descriptions-item label="处理建议">
                <ul class="treatment-list">
                  <li v-for="(item, index) in result.treatment" :key="index">
                    <el-icon><check /></el-icon>{{ item }}
                  </li>
                </ul>
              </el-descriptions-item>
            </el-descriptions>
          </el-card>

          <el-skeleton v-else-if="loading" :rows="5" animated />

          <div v-else class="empty-result">
            <el-icon><document /></el-icon>
            <p>识别结果将在此处显示</p>
          </div>
        </div>
      </div>

      <!-- 历史记录 -->
      <div class="history-section">
        <h3 class="section-title">识别历史</h3>
        <el-scrollbar>
          <div class="history-list">
            <div
                v-for="(record, index) in history"
                :key="index"
                class="history-item"
                @click="showHistoryDetail(record)"
            >
              <div class="item-thumbnail">
                <img :src="record.image" alt="History" />
              </div>
              <div class="item-info">
                <div class="info-main">
                  <span class="disease-name">{{ record.name }}</span>
                  <el-tag size="small" type="success">
                    {{ (record.confidence).toFixed(1) }}%
                  </el-tag>
                </div>
                <div class="info-time">{{ record.timestamp }}</div>
              </div>
            </div>
          </div>
        </el-scrollbar>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import MonitorRealtime from '@/views/Monitor/MonitorRealtime.vue';
import { ref, onMounted, onBeforeUnmount } from 'vue'
import Hls from 'hls.js' // 引入 hls.js
import { Camera, UploadFilled, PictureFilled, Document, Check } from '@element-plus/icons-vue'
import type { UploadFile } from 'element-plus'
import request from "@/util/request.ts";

interface DetectionResult {
  name: string
  description: string
  treatment: string[]
  confidence: number
  timestamp: string
  image: string
}

interface HistoryRecord extends Omit<DetectionResult, 'treatment'> {
  treatment: string
}

const uploadedImage = ref('')
const fileName = ref('')
const uploadTime = ref('')
const result = ref<DetectionResult | null>(null)
const loading = ref(false)
const history = ref<HistoryRecord[]>([])
const maxMB = ref(2);

// 视频播放器相关
const videoPlayer = ref<HTMLElement | null>(null)
let hlsPlayer: any = null // 定义 hls 播放器实例

// 初始化历史记录
onMounted(() => {
  initVideoPlayer()
  const savedHistory = localStorage.getItem('pestHistory')
  if (savedHistory) {
    history.value = JSON.parse(savedHistory)
  }
})

// 添加 onBeforeUnmount
onBeforeUnmount(() => {
  if (hlsPlayer) {
    hlsPlayer.destroy()
  }
})

// 初始化视频播放器
const initVideoPlayer = () => {
  if (videoPlayer.value) {
    if (Hls.isSupported()) {
      hlsPlayer = new Hls()
      hlsPlayer.loadSource('/temp/temp.m3u8') // 替换为实际的视频流地址
      hlsPlayer.attachMedia(videoPlayer.value as HTMLVideoElement)
      hlsPlayer.on(Hls.Events.MEDIA_ATTACHED, () => {
        (videoPlayer.value as HTMLVideoElement).play()
      })
    } else if ((videoPlayer.value as HTMLVideoElement).canPlayType('application/vnd.apple.mpegurl')) {
      (videoPlayer.value as HTMLVideoElement).src = '/temp/temp.m3u8'
      (videoPlayer.value as HTMLVideoElement).addEventListener('canplay', () => {
        (videoPlayer.value as HTMLVideoElement).play()
      })
    }
  }
}

// 添加截图功能
const captureSnapshot = async () => {
  if (!hlsPlayer) return

  const video = hlsPlayer.media
  const canvas = document.createElement('canvas')
  // canvas.width = video.videoWidth
  // canvas.height = video.videoHeight
  // canvas.getContext('2d')?.drawImage(video, 0, 0)

  // 指定截图的宽度和高度
  const width = 1000;
  const height = 1000 / (video.videoWidth / video.videoHeight);
  canvas.width = width;
  canvas.height = height;

  const ctx = canvas.getContext('2d');
  if (ctx) {
    // 计算视频的缩放比例，以确保视频内容完整显示在截图中
    const videoAspectRatio = video.videoWidth / video.videoHeight;
    const canvasAspectRatio = width / height;

    let sourceX = 0;
    let sourceY = 0;
    let sourceWidth = video.videoWidth;
    let sourceHeight = video.videoHeight;

    if (videoAspectRatio > canvasAspectRatio) {
      // 视频宽度相对较大，需要裁剪左右部分
      sourceWidth = video.videoHeight * canvasAspectRatio;
      sourceX = (video.videoWidth - sourceWidth) / 2;
    } else {
      // 视频高度相对较大，需要裁剪上下部分
      sourceHeight = video.videoWidth / canvasAspectRatio;
      sourceY = (video.videoHeight - sourceHeight) / 2;
    }

    // 将视频内容绘制到画布上
    ctx.drawImage(video, sourceX, sourceY, sourceWidth, sourceHeight, 0, 0, width, height);
  }


  const dataURL = canvas.toDataURL('image/png')
  const blob = await (await fetch(dataURL)).blob()

  const file = new File([blob], 'snapshot.png', {
    type: 'image/png',
    lastModified: Date.now()
  })

  handleImageUpload({
    uid: Date.now(),
    name: 'snapshot.png',
    status: 'success',
    raw: file,
    size: blob.size,
  } as UploadFile)
}
const name = ref('');
const name1 = ref('');

const form1 = ref({
  description: '',
  chemistry: '',
  creature: '',
  agriculture: ''
});
let valueee = 0;
const handleImageUpload = async (file: UploadFile) => {
  //设置判断文件上传大小
  const maxSize = maxMB.value * 1024 * 1024;
  if (file.size > maxSize) {
    alert(`文件大小超过限制，最大允许 ${maxSize / (1024 * 1024)}MB`);
    return;
  }

  // 给详细信息赋予null就会虚化条
  result.value = null;
  loading.value = true

  // 处理图片预览
  const reader = new FileReader()
  let valuefile:string = "pl pk"
  reader.onload = (e) => {
    valuefile = e.target?.result as string
    // console.log(valuefile)
    uploadedImage.value = valuefile
    fileName.value = file.name
    uploadTime.value = new Date().toLocaleString()

    // fetch('http://172.16.76.185:8898/refs', {
    //   method: 'POST',
    //   body: valuefile
    // }).then(response => {
    //   if (response.ok) {
    //     return response.text(); // 如果请求成功，根据响应内容类型选择合适的方法（如 text()、json()、blob() 等）获取数据
    //   }
    //   throw new Error('请求失败');
    // })
    //     .then(data => {
    //       console.log('请求成功，响应数据:', data);
    //     })
    // ;

    fetch('/reqstart.zsj/postimg', {
      method: 'POST',
      body: valuefile
    })
        .then(response => {
          if (response.ok) {
            return response.json(); // 如果请求成功，根据响应内容类型选择合适的方法（如 text()、json()、blob() 等）获取数据
          }
          throw new Error('请求失败');
        })
        .then(data => {
          console.log('请求成功，响应数据:', data);
          //const res = JSON.parse(data)
          const res = data;
          //console.log(res)
          name1.value = res.name
          name.value = res.name
          valueee = res.confidence


          if (res.name != "null") {
            //C++后端返回的图片数据，注释掉即可不显示
            uploadedImage.value = data.base;
            request.get('/api/illness/get?name=' + name1.value).then(res =>{
              if (res.data.code === '200'){
                console.log(res.data)
                form1.value.description = res.data.data.description
                form1.value.chemistry = res.data.data.chemistry
                form1.value.creature = res.data.data.creature
                form1.value.agriculture = res.data.data.agriculture

                // 模拟返回数据
                const mockResult = {
                  name: name.value,
                  description: form1.value.description,
                  treatment: [
                    form1.value.chemistry,
                    form1.value.creature,
                    form1.value.agriculture
                  ],
                  confidence: valueee,
                  timestamp: new Date().toLocaleString(),
                  image: uploadedImage.value
                }
                //赋予详细信息的值，会退出虚化条状态
                result.value = mockResult
                addToHistory(mockResult)
              }
            })
          }
          else {
            name.value = "未识别图片的植物"
            form1.value.description = "未识别图片的病虫害"
            form1.value.chemistry = "未识别图片的病虫害无法提供建议1"
            form1.value.creature = "未识别图片的病虫害无法提供建议2"
            form1.value.agriculture = "未识别图片的病虫害无法提供建议3"

            // 模拟返回数据
            const mockResult = {
              name: name.value,
              description: form1.value.description,
              treatment: [
                form1.value.chemistry,
                form1.value.creature,
                form1.value.agriculture
              ],
              confidence: valueee,
              timestamp: new Date().toLocaleString(),
              image: uploadedImage.value
            }
            result.value = mockResult
            addToHistory(mockResult)
          }
        })
        .catch(error => {
          console.error('请求出错:', error);
        });




  }
  reader.readAsDataURL(file.raw!)
  console.log(uploadedImage)


  // const str = '/reqstart.zsj';
  // request.get(str).then(res =>{
  //   console.log(res.data)
  //   name1.value = res.data.name
  //   name.value = res.data.name
  //   valueee = res.data.confidence
  //   if (res.data.name != "null") {
  //     request.get('/api/illness/get?name=' + name1.value).then(res =>{
  //       if (res.data.code === '200'){
  //         console.log(res.data)
  //         form1.value.description = res.data.data.description
  //         form1.value.chemistry = res.data.data.chemistry
  //         form1.value.creature = res.data.data.creature
  //         form1.value.agriculture = res.data.data.agriculture
  //       }
  //     })
  //   }
  //   else {
  //     name.value = "未识别图片的植物"
  //     form1.value.description = "未识别图片的病虫害"
  //     form1.value.chemistry = "未识别图片的病虫害无法提供建议1"
  //     form1.value.creature = "未识别图片的病虫害无法提供建议2"
  //     form1.value.agriculture = "未识别图片的病虫害无法提供建议3"
  //   }
  // })
  // 模拟API调用
  //await new Promise(resolve => setTimeout(resolve, 10000))
  // 模拟返回数据
  // const mockResult = {
  //   name: name.value,
  //   description: form1.value.description,
  //   treatment: [
  //     form1.value.chemistry,
  //     form1.value.creature,
  //     form1.value.agriculture
  //   ],
  //   confidence: valueee,
  //   timestamp: new Date().toLocaleString(),
  //   image: uploadedImage.value
  // }
  // result.value = mockResult
  // addToHistory(mockResult)
}

const addToHistory = (data: DetectionResult) => {
  const historyItem: HistoryRecord = {
    name: data.name,
    description: data.description,
    confidence: data.confidence,
    timestamp: data.timestamp,
    image: data.image,
    treatment: data.treatment.join('；')
  }

  history.value.unshift(historyItem)
  if (history.value.length > 10) history.value.pop()
  localStorage.setItem('pestHistory', JSON.stringify(history.value))
}

const showHistoryDetail = (record: HistoryRecord) => {
  result.value = {
    ...record,
    treatment: record.treatment.split('；'),
    image: record.image
  }
  uploadedImage.value = record.image
}

</script>

<style scoped lang="scss">
.pest-management-container {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
  box-sizing: border-box;

  .video-section {
    margin-bottom: 2rem;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);

    .video-container {
      position: relative;
      background: #000;
      width: 100%; // 让容器宽度占满父元素
      padding-top: 56.25%; // 保持 16:9 的宽高比，可根据实际需要调整
      .screenshot-btn {
        position: absolute;
        bottom: 20px;
        right: 20px;
        z-index: 100;

        .el-button {
          width: 48px;
          height: 48px;
          font-size: 24px;
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }
      }
    }
    video {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      &::-webkit-media-controls {
        display: none !important;
      }
      &::-webkit-media-controls-enclosure {
        display: none !important;
      }
      &::-webkit-media-controls-panel {
        display: none !important;
      }
      &::-webkit-media-controls-play-button {
        display: none !important;
      }
      &::-webkit-media-controls-timeline {
        display: none !important;
      }
      &::-webkit-media-controls-current-time-display {
        display: none !important;
      }
      &::-webkit-media-controls-time-remaining-display {
        display: none !important;
      }
      &::-webkit-media-controls-mute-button {
        display: none !important;
      }
      &::-webkit-media-controls-volume-slider {
        display: none !important;
      }
      &::-webkit-media-controls-fullscreen-button {
        display: none !important;
      }
    }
  }

  .upload-container {
    margin-bottom: 2rem;

    :deep(.el-upload-dragger) {
      border: 2px dashed var(--el-color-success);
      background: rgba(103, 194, 58, 0.05);
      padding: 2.5rem 1rem;
      transition: all 0.3s;

      &:hover {
        border-color: var(--el-color-success-dark-2);
        background: rgba(103, 194, 58, 0.1);
      }
    }

    .upload-content {
      display: flex;
      flex-direction: column;
      align-items: center;

      .upload-icon {
        font-size: 3.5rem;
        color: var(--el-color-success);
        margin-bottom: 1rem;
      }

      .upload-main {
        font-size: 1.2rem;
        color: var(--el-text-color-primary);
        margin-bottom: 0.5rem;
      }

      .upload-sub {
        font-size: 0.9rem;
        color: var(--el-text-color-secondary);
      }
    }
  }

  .main-content {
    width: 100%;
    display: grid;
    grid-template-columns: 2fr 1fr;
    gap: 2rem;
    align-items: start;

    .analysis-section {
      display: grid;
      gap: 1.5rem;
      position: sticky;
      top: 2rem;

      .preview-card {
        border-radius: 12px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
        overflow: hidden;
        border: 2px dashed var(--el-border-color);

        img {
          width: 100%;
          height: auto;
          max-height: 600px;
          object-fit: contain;
          padding: 1rem;
        }

        .image-info {
          padding: 1rem;
          display: flex;
          justify-content: space-between;
          font-size: 0.9rem;
          border-top: 1px solid var(--el-border-color-light);

          .file-name {
            color: var(--el-text-color-primary);
          }

          .upload-time {
            color: var(--el-text-color-secondary);
          }
        }
      }

      .result-card {
        border-radius: 12px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);

        :deep(.el-card__header) {
          border-bottom: none;
          padding: 1.5rem;

          .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;

            .disease-name {
              font-size: 1.3rem;
              color: var(--el-text-color-primary);
            }
          }
        }

        .treatment-list {
          li {
            margin: 0.5rem 0;
            display: flex;
            align-items: center;

            .el-icon {
              margin-right: 0.5rem;
              color: var(--el-color-success);
            }
          }
        }
      }
    }

    .history-section {
      border: 2px dashed var(--el-border-color-light);
      border-radius: 12px;
      padding: 1.5rem;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
      height: 100%;
      display: flex;
      flex-direction: column;

      .section-title {
        margin: 0 0 1.5rem;
        color: var(--el-text-color-primary);
        font-size: 1.2rem;
        flex-shrink: 0;
      }

      .el-scrollbar {
        flex: 1;
        height: 100%;
      }

      .history-list {
        padding-right: 0.5rem;

        .history-item {
          display: flex;
          padding: 1rem;
          margin-bottom: 1rem;
          border-radius: 8px;
          cursor: pointer;
          transition: all 0.2s;
          border: 1px solid var(--el-border-color-light);

          &:hover {
            transform: translateX(4px);
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
          }

          .item-thumbnail {
            width: 60px;
            height: 60px;
            margin-right: 1rem;
            flex-shrink: 0;

            img {
              width: 100%;
              height: 100%;
              object-fit: cover;
              border-radius: 6px;
            }
          }

          .item-info {
            flex: 1;

            .info-main {
              display: flex;
              justify-content: space-between;
              align-items: center;
              margin-bottom: 0.5rem;

              .disease-name {
                font-size: 0.95rem;
                color: var(--el-text-color-primary);
              }
            }

            .info-time {
              font-size: 0.8rem;
              color: var(--el-text-color-secondary);
            }
          }
        }
      }
    }
  }

  .empty-preview, .empty-result {
    height: 300px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: var(--el-text-color-secondary);
    padding: 2rem;
    border: 2px dashed var(--el-border-color);
    border-radius: 12px;

    .el-icon {
      font-size: 3rem;
      margin-bottom: 1rem;
      color: var(--el-color-success-light-3);
    }
  }
}

@media (max-width: 992px) {
  .pest-management-container {
    padding: 1rem;

    .video-section {
      margin: 0 -1rem 2rem;
      border-radius: 0;

      .video-container {
        .screenshot-btn {
          bottom: 10px;
          right: 10px;

          .el-button {
            width: 40px;
            height: 40px;
            font-size: 20px;
          }
        }
      }
    }

    .main-content {
      grid-template-columns: 1fr !important;
      gap: 1rem;

      .analysis-section {
        position: static;
      }

      .history-section {
        max-height: 500px;
      }
    }
  }
}
</style>
